package com.data_structure_algorithm.data_structure.hash;

import java.util.Objects;

/**
 * @Authror PABLO
 * @Date 2022/3/28 15:22
 * @Desc 哈希表
 */
public class HashTable {

    EmpLinkedList[] linkedLists;

    int hashTableMax;

    public HashTable(int hashTableMax) {
        this.linkedLists = new EmpLinkedList[hashTableMax];
        this.hashTableMax = hashTableMax;
    }

    public void add(Emp emp) {
        if (!Objects.isNull(emp)) {
            EmpLinkedList hash = hash(emp.id);
            hash.add(emp);
        }


    }

    public void update(Emp emp) {
        if (!Objects.isNull(emp)) {
            EmpLinkedList hash = hash(emp.id);
            hash.update(emp);
        }
    }

    public void remove(Emp emp) {
        if (!Objects.isNull(emp)) {
            EmpLinkedList hash = hash(emp.id);
            hash.remove(emp);
        }

    }

    public void find(int id) {
        EmpLinkedList hash = hash(id);
        hash.find(id);
    }

    public void print() {
        for (EmpLinkedList item : linkedLists
        ) {
            System.out.println();
            if (!Objects.isNull(item)) {

                item.print();
            }
        }
    }

    /**
     * @Description: 计算hash散列值, 即当前id对应的链表
     * @Author: PABLO
     * @Date: 2022/3/28 15:31
     * @Params: [id]
     * @Return: com.learn.data.hash.EmpLinkedList
     **/
    public EmpLinkedList hash(int id) {
        //根据id获取对应链表
        int index = id % hashTableMax;
        //判断是否为空
        EmpLinkedList linkedList = linkedLists[index];

        if (Objects.isNull(linkedList)) {
            //创建下标对应的链表
            for (int i = 0; i < linkedLists.length; i++) {
                if (index == i) {
                    linkedLists[i] = new EmpLinkedList();

                }
            }
            linkedLists[index].index = index;
            return linkedLists[index];
        }

        return linkedList;
    }

}
